<template>
	<view class="container parent">
		<view class="card">
			<view class="row">
				<view class="label">商品名称</view>
				<uni-easyinput placeholder="请填写商品名称" v-model="title" trim="both" />
			</view>
			<view class="row">
				<view class="label">商品价格</view>
				<view class="price">
					<view class="price-label">￥</view>
					<uni-easyinput placeholder="请填写商品价格" @input="num($event)" type="digit" v-model="price" class="price-input" />
				</view>
			</view>
			<view class="row">
				<view class="label">商品规格</view>
				<uni-easyinput placeholder="比如1件1000g,500g,1斤等" v-model="specific" class="price-input" />
			</view>
			<view class="row">
				<view class="label">商品库存</view>
				<uni-easyinput placeholder="请填写商品库存" v-model="goods.stock" class="price-input" />
			</view>
		</view>
		<view class="card">
			<uni-file-picker v-model="insideImg" :limit="1" :source-type="['album', 'camera']" return-type="object" file-extname="png,jpg" @fail="fail">商品图片</uni-file-picker>
			<view class="row category">
				<view class="label">商品分类</view>
				<view class="sel" @click="nav('/pages/merchant/category')">
					<view class="placeholder">{{ goods.category_id ? getGoodsCategory : '请选择商品分类' }}</view>
					<uni-icons type="right" size="20" color="#BBBBBB" />
				</view>
			</view>
		</view>
		<view class="card">
			<view class="row">商品描述</view>
			<uni-easyinput type="textarea" v-model="goods.des" autoHeight placeholder="(选填)请填写商品详细描述" :maxlength="2000" />
		</view>
		<view class="space" />
		<uni-popup ref="alert" type="message">
			<uni-popup-message :type="toastType" :message="content" />
		</uni-popup>

		<view class="ops">
			<view class="btn save" @click="saveAndBack">保存</view>
			<view class="btn add" @click="saveAndAdd">保存并添加</view>
		</view>
	</view>
</template>

<script lang="ts" setup>
import { nextTick, ref ,computed } from 'vue';
import { onShow, onLoad, onUnload } from '@dcloudio/uni-app';
import { state, setCategory, setGoods } from '../../store/global';
import { state as shopState } from '../../store/shop';
import getGoods from '../../vendor/order_food/goods';

import getCategory, { Category } from '../../vendor/order_food/category';
import { trimAllSpace } from '@/common/util';
const { goods, add, update } = getGoods();

const price = ref('');

const { list: categoryList, getList: getCategoryList } = getCategory();

const title = ref(''); // 商品标题
const specific = ref(''); // 商品规格
onLoad(() => {
	goods.value = JSON.parse(JSON.stringify(state.goods));

	// 标题去掉规格
	const t = goods.value.title.split("|")
	
	title.value = trimAllSpace(t.length > 1 ? t[1]:t[0]);
	specific.value = trimAllSpace(t.length > 1 ? t[0]:'');

	price.value = (goods.value.price / 100).toFixed(2);
	if (goods.value.id) {
		// 修改
		uni.setNavigationBarTitle({
			title: '编辑商品'
		});

		insideImg.value = {
			name: '',
			// url: env.clound_storage_url + goods.value.img
			url: goods.value.img
		};

		getCategoryList(() => {
			const category: Category = categoryList.value.find((item) => {
				if (item.id == goods.value.category_id) {
					return true;
				}
			});

			setCategory(category);
		});
	} else {
		// 添加
		uni.setNavigationBarTitle({
			title: '添加商品'
		});
	}
});

const getGoodsCategory = computed( () => {
	console.log(shopState.categoryList);
	const item = shopState.categoryList.find((ob) => ob.id == goods.value.category_id);
	return item?item.title:'';
});

onShow(() => {
	if (state.category.id) {
		console.log(state.category.id);
		goods.value.category_id = state.category.id;
		console.log(goods.value);
	}
});

onUnload(() => {
	console.log('初始化');
	init();
});

const init = () => {
	setCategory({
		id: 0,
		title: '',
		sort: 0
	});

	setGoods({
		id: 0,
		title: '',
		img: '',
		category_id: 0,
		status: 1,
		des: '',
		price: 0,
		stock: 9999999,
	});

	insideImg.value = null;

	goods.value.title = '';
	goods.value.img = '';
	goods.value.category_id = 0;

	goods.value.des = '';
	price.value = '';

	goods.value.price = 0;
	goods.value.stock = 9999999;
	goods.value.id = 0;

	console.log(goods.value);
};

type Img = {
	name: string;
	url: string;
};
const insideImg = ref<Img>(null);
const content = ref('');
const toastType = ref('error');
const alert = ref(null);

const fail = (e) => {
	content.value = '上传失败,请稍后重试';
	toastType.value = 'error';
	alert.value.open();
};

const nav = (url: string) => {
	uni.navigateTo({
		url
	});
};

const toasting = (title) => {
	uni.showToast({
		title,
		icon: 'none'
	});
};

const save = (cal: Function = () => {}) => {
	console.log(insideImg.value);
	// 判断条件(标题、规格、分类)
	if (!trimAllSpace(title.value)) {
		toasting('请填写标题');
		return;
	}

	if (!trimAllSpace(specific.value)) {
		toasting('请填写商品规格');
		return;
	}

	if (!price.value || parseFloat(price.value) == 0) {
		toasting('请填写商品价格');
		return;
	}

	if (!goods.value.stock) {
		toasting('请填写库存');
		return;
	}

	if (!Number.isInteger(Number(goods.value.stock))) {
		toasting('库存为整数');
		return;
	}

	goods.value.price = parseFloat(price.value);

	// 图片
	if (insideImg.value) {
		goods.value.img = insideImg.value.url;
	}

	if (!goods.value.img) {
		toasting('请上传商品主图');
		return;
	}

	// 分类
	if (!goods.value.category_id) {
		toasting('请填写分类');
		return;
	}

	if (goods.value.id) {
		goods.value.title = `${specific.value} | ${title.value}`;

		// 修改
		update(() => {
			state.goods.title = goods.value.title;
			state.goods.price = goods.value.price * 100;
			state.goods.stock = goods.value.stock;
			state.goods.img = goods.value.img;
			state.goods.category_id = goods.value.category_id;
			state.goods.des = goods.value.des;

			toasting('编辑成功');
			cal();
		});
	} else {
		// 添加
		// 规格和标题相合
		goods.value.title = `${specific.value} | ${title.value}`;
		add((res: any) => {
			toasting('添加成功');
			goods.value.id = res.id;

			// 找到分类
			const item = shopState.goodsList.find((ob) => ob.id == goods.value.category_id);
			if (item) {
				goods.value.price = goods.value.price * 100;
				if (item.goods_list) {
					item.goods_list.push(JSON.parse(JSON.stringify(goods.value)));
				} else {
					item.goods_list = [];
					item.goods_list.push(JSON.parse(JSON.stringify(goods.value)));
				}
			}

			cal();
		});
	}
};

const saveAndBack = () => {
	save(() => {
		uni.navigateBack();
	});
};

const saveAndAdd = () => {
	save(() => {
		init();
	});
};

const num = (e: string, index: number) => {
	e = e.match(/^\d*(\.?\d{0,2})/g)[0] || null;
	nextTick(() => {
		price.value = e;
	});
};
</script>

<style lang="scss" scoped>
.card {
	background: white;
	padding: 20px;
	border-radius: 20px;
	margin-bottom: $uni-spacing-row-lg;

	.row {
		display: flex;
		margin-bottom: 10px;

		.label,
		.price-label {
			height: 35px;
			line-height: 35px;
		}

		.label {
			margin-right: 20px;
		}

		.price {
			display: flex;
		}
	}
}

:deep .is-input-border {
	border: 0 !important;
}

:deep .uni-easyinput__content-input {
	padding-left: 0 !important;
}

.sel {
	display: flex;
	justify-content: space-between;
	width: calc(100% - 90px);
	line-height: 35px;

	.placeholder {
		color: #bbbbbb;
	}
}

:deep .uni-easyinput__placeholder-class {
	font-size: 15px;
}

.goods-img-option {
	text-align: center;
}

.category {
	margin-top: 10px;
}

.space {
	height: 100px;
}

.ops {
	background: white;
	display: flex;
	padding-top: 10px;
	position: fixed;
	left: 0;
	bottom: 0;
	width: 100%;
	height: 100px;
	z-index: 999;
	.btn {
		text-align: center;
		color: white;
		line-height: 50px;
		height: 50px;
		width: 45%;
		margin: 0 auto;
		border-radius: $uni-border-radius-lg;
	}

	.save {
		background: #e8e460;
	}

	.add {
		background: #a5d63f;
	}
}

.property-title {
	font-size: 15px;
	color: #bbbbbb;
}

.property {
	font-size: 15px;
}

.sep {
	border: 1px solid #f5f5f5;
	width: 90%;
	margin: 0 auto;
	margin: 10px;
}

.tab-header,
.columns {
	display: flex;
	justify-content: space-between;
}
.header,
.column {
	width: 33%;
}

.columns {
	margin-top: 10px;
}

// .template {
// 	padding: 0 30px;
// }
.inventory {
	width: 35%;
	display: flex;
	line-height: 35px;
}

.tags {
	display: flex;
	flex-wrap: wrap;

	.tag {
		background: #efefef;
		color: #a6a6a6;
		line-height: 35px;
		border-radius: 5px;
		min-width: calc(100% / 3 - 20px);
		padding: 0 5px;
		text-align: center;
		margin-right: 5px;
		margin-bottom: 5px;
		color: black;
	}
}

.add-specs {
	.btn {
		color: blue;
		line-height: 35px;
	}

	justify-content: space-between;
}
</style>
